package com.jin.utils;

/**
 * Created on 2025/4/1.
 * @author Zhongyuan Jin
 */


import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;

@RestController
@RequestMapping("/api")
public class FileController {

    @Value("${spring.servlet.multipart.location}")
    private String uploadDir;

    private static final String[] ALLOWED_FILE_TYPES = { "image/jpeg", "image/png", "image/gif" };
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("上传文件为空，请选择文件后再次上传。");
            }

            // 检查文件类型是否在允许列表中
            if (!Arrays.asList(ALLOWED_FILE_TYPES).contains(file.getContentType())) {
                return ResponseEntity.badRequest().body("不允许上传该类型的文件，请上传图片文件（jpg、jpeg、png、gif）。");
            }

            // 检查文件大小是否超过限制
            if (file.getSize() > MAX_FILE_SIZE) {
                return ResponseEntity.badRequest().body("上传文件过大，单个文件大小不能超过 5MB。");
            }

            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 获取文件名
            String originalFileName = file.getOriginalFilename();
            // 获取文件后缀名
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            // 生成唯一文件名，使用当前时间戳
            String uniqueFileName = System.currentTimeMillis() + fileExtension;
            // 构建文件路径
            Path filePath = uploadPath.resolve(uniqueFileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回文件的URI
            String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/api/download/")
                    .path(uniqueFileName)
                    .toUriString();

            return ResponseEntity.ok("文件上传成功: " + fileDownloadUri);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            // 构建文件路径
            Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();

            // 检查文件是否存在
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }

            // 创建资源
            Resource resource = new UrlResource(filePath.toUri());

            // 返回文件
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }
}
